;
(function (window, document, $, undefined) {

    let idArr = JSON.parse(localStorage.getItem("shoppingCar") || '[]'),
        cookieGet = $.cookie('loginToken'),
        jsArr = [],
        dataArr = [],
        shopToken = $.cookie('loginToken'),
        xgjsAJaxArr = [],
        userArr = [];
    init()

    //登录退出///////////////////////////////
    let baseUrl = 'http://localhost:2020'

    isToken()

    // 退出登录，显示遮罩层
    $('.logout').on('click', function () {
        $('.logout-wp').show()
    })

    $('.close').on('click', function () {
        $('.logout-wp').hide()
    })

    $('.define').on('click', function () {
        logoutFn(cookieGet)
        $.cookie('loginToken', '');
        $('.logout-wp').hide()
        isToken()
    })

    // 导航条的点击事件
    $('.teacherlibox').on('click', function () {
        $('.teacherpullBox').toggle()
    })

    // 用户的点击事件
    $('.userliBox').on('click', function () {
        $('.userpullBox').toggle()
    })

    // 点击body导航条里的ol隐藏
    $('body').on('click', function (e) {
        if (e.target.className != "teacherlibox") {
            $('.teacherpullBox').hide()
        }
        if (e.target.className != "userliBox") {
            $('.userpullBox').hide()
        }
    })

    //退出登录
    function logoutFn(token) {
        $.ajax({
            url: baseUrl + '/user/logout',
            type: 'post',
            data: {
                token
            },
            success: function (res) {
                console.log(res)
            }
        })
    }

    // 是否有token
    function isToken() {
        if (!$.cookie('loginToken')) {
            $('.login').show()
            $('.logon').show()
            $('.userliBox').hide()
        } else {
            $('.login').hide()
            $('.logon').hide()
            $('.userliBox').show()
        }
    }


    //三级联动
    let $shen = $("#shen"),
        datas = data,
        wxArr = [];
    $("#shen").on("change", function () {
        var value = $(this);
        chang($("#shi"), datas, value)
    })

    $("#shi").on("change", function () {
        var value = $(this);
        chang($("#qu"), wxArr, value)
    })

    $("#qu").on("change", function () {
        if ($(this).val() == "0") {
            chang(1, 2, $(this))
        }
    })

    function chang(a, b, c) {
        if (c.val() == "0" || a == 1) {
            c.siblings().val("0")
            return;
        }
        wxArr = b.filter(function (v, i) {
            return v.value == c.val();
        })[0].children;
        xrsel(a, wxArr)
    }

    xrsel($shen, datas)

    function xrsel(a, b) {
        var wxArr1 = [];
        wxArr1.push("<option value='0'>请选择</option>")
        for (var i = 0; i < b.length; i++) {
            wxArr1.push("<option data-city='", b[i].text, "' value=", b[i].value, ">", b[i].text, "</option>")
        }
        a.html(wxArr1.join(""));
    }
    //加号
    $(".nav-content-shop").on("click", ".jia", function (e) {
        var ind = $(this).attr("data-i")
        var parent = $(".nav-content-shop").find(".nav-content-sp").eq(ind) //拿到父盒子
        var num = parent.find(".sp").text() * 1
        var jg = parent.find(".jiage").text() * 1
        var jg1 = parent.find(".jiage1").text() * 1
        // var zj = $(".nav-content-btn-jq").text() * 1
        // var dj = parent.find(".jiage").text() * 1
        num += 1
        // console.log(zj)
        // zj+=dj
        // $(".nav-content-btn-jq").text(zj)
        jg = num * jg1
        parent.find(".sp").text(num)
        parent.find(".jiage").text(jg)
    })

    //减号
    $(".nav-content-shop").on("click", ".jian", function (e) {
        var ind = $(this).attr("data-i")
        var parent = $(".nav-content-shop").find(".nav-content-sp").eq(ind) //拿到父盒子
        var num = parent.find(".sp").text() * 1
        var jg = parent.find(".jiage").text() * 1
        var jg1 = parent.find(".jiage1").text() * 1
        if (num == 1) {
            return
        }
        num -= 1
        jg = jg - jg1
        parent.find(".sp").text(num)
        parent.find(".jiage").text(jg)
    })

    //全选
    $(".gxkAll").on("change", function () {
        var isTure = this.checked
        var Btn = $(".jsBtn")
        var ipt = $(".gxk")
        var djs = $(".jiage")
        var zj = $('.nav-content-btn-jq')
        var num = 0
        var nums = $('.sp')
        jsArr = []
        for (var i = 0; i < djs.length; i++) {
            num += djs.eq(i).text() * 1
        }
        if (isTure) {
            $('.nav-content-sp').addClass('yellow')
            zj.text(num)
            Btn.addClass("red")
        } else {
            $('.nav-content-sp').removeClass('yellow')
            zj.text(0)
            Btn.removeClass("red")
        }
        for (var i = 0; i < ipt.length; i++) {
            ipt.eq(i).prop("checked", isTure)
        }
        if (isTure) {
            for (var i = 0; i < ipt.length; i++) {
                jsArr.push({
                    id: ipt.eq(i).attr("data-id"),
                    num: nums.eq(i).text() * 1
                })
            }
        }
    })

    //多删
    $('.delDatas').on("click", function () {
        if ($('.gxkAll:checked').length) {
            let ids = idArr.map(v => v.bookId)
            delDataAjax(ids.join(","))
            idArr = [];
            localStorage.setItem('shoppingCar', JSON.stringify(idArr))
            getData(idArr)
        }
    })

    //单选
    $(".nav-content-shop").on("change", ".gxk", function (e) {
        var ind = $(this).attr("data-i")
        var id = $(this).attr("data-id")
        var parent = $(".nav-content-shop").find(".nav-content-sp").eq(ind)
        var isTure = $(this).prop("checked")
        var zj = $(".nav-content-btn-jq").text() * 1
        var dj = parent.find(".jiage").text() * 1
        var Btn = $(".jsBtn")
        var num = parent.find('.sp').text()
        $(".gxkAll").prop("checked", (!$(".gxk").not("input:checked").length))
        if (isTure) {
            jsArr.push({
                id: id,
                num: num
            })
            var Allzj = zj += dj
            parent.addClass("yellow")
            $(".nav-content-btn-jq").text(Allzj)
            Btn.addClass("red")
        } else {
            let ind = jsArr.indexOf(id * 1)
            jsArr.splice(ind, 1)
            zj -= dj
            parent.removeClass("yellow")
            $(".nav-content-btn-jq").text(zj)
            Btn.removeClass("red")
        }
        console.log(jsArr)
    })

    //删除
    $(".nav-content-shop").on("click", ".delData", function () {
        var ind = $(this).attr("data-i")
        var parent = $(".nav-content-shop").find(".nav-content-sp").eq(ind)
        var id = parent.find(".delData").attr("data-id")
        var ids = idArr.map(v => {
            return v.bookId
        });
        var index = ids.indexOf(id)
        let localArr = idArr.filter(v => {
            return v.bookId != id
        });
        ids.splice(index, 1)
        $(".nav-content-btn-jq").text(0)
        $(".gxkAll").prop("checked", false)
        delDataAjax(id)
        localStorage.setItem('shoppingCar', JSON.stringify(localArr))
        getData(ids)
    })

    //发送删除请求
    function delDataAjax(id) {
        $.ajax({
            url: "http://localhost:2020/jiesuan/delList",
            type: "GET",
            data: {
                cid: id
            },
            success(res) {
                // console.log(res)
            }
        })
    }


    //打开遮造层
    $(".jsBtn").on("click", function () {
        dizhiArr = [];
        $('.js-wp-you-name').text(userArr.name)
        if (userArr.area) {
            dizhiArr = JSON.parse(userArr.area)
            $(`#shen option[data-city=${dizhiArr[0]}]`).attr('selected', true)
            chang($("#shi"), datas, $('#shen'))
            $(`#shi option[data-city=${dizhiArr[1]}]`).attr('selected', true)
            chang($("#qu"), wxArr, $("#shi"))
            $(`#qu option[data-city=${dizhiArr[2]}]`).attr('selected', true)
        }
        if ($(".gxk:checked").length) {
            var zj = $('.nav-content-btn-jq').text() * 1
            var xrArr = [];
            $(".Allzj").text(zj + '.00')
            var zzc = $(".zzc-wp")
            for (var i = 0; i < dataArr.length; i++) {
                for (var o = 0; o < jsArr.length; o++) {
                    if (dataArr[i].id == jsArr[o].id) {
                        dataArr[i].num = jsArr[o].num
                        xrArr.push(dataArr[i])
                    }
                }
            }
            xgjsAJaxArr = xrArr
            xrjs(xrArr)
            zzc.css({
                display: "block"
            })
        }

    })

    //关闭遮罩层
    $(".qxfk").on("click", function () {
        var parent = $(".zzc-wp")
        parent.css({
            display: "none"
        })
        $('.name').val("")
        $('.Allzj').text(0)
    })

    function init() {
        if (idArr.length) {
            var id = idArr.map(v => {
                return v.bookId
            });
            getData(id)
        } else {
            getData([])
        }
        getInfo(shopToken)
    }

    //确定给钱
    $(".geiqian").on("click", function () {
        let shen, shi, qu, area = [],
            newArr = [],
            indArr = [],
            abc = [],
            idArr = JSON.parse(localStorage.getItem('shoppingCar'));
        shen = $("#shen option:checked").attr("data-city")
        shi = $("#shi option:checked").attr("data-city")
        qu = $("#qu option:checked").attr("data-city")
        area.push(shen, shi, qu)
        // console.log(idArr[0].indexOf(jsArr[0].id)) jsArr idArr
        indArr = idArr.map(v => {
            return v.bookId
        }) //购物车所有商品id
        newArr = jsArr.map(v => {
            return v.id
        }) //已购的商品id
        for (var i = 0; i < indArr.length; i++) {
            if (newArr.indexOf(indArr[i]) < 0) {
                abc.push(indArr[i])
            }
        }
        idArr = idArr.filter(v => {
            return v.bookId == abc.find(o => v.bookId == o)
        })
        localStorage.setItem("shoppingCar", JSON.stringify(idArr))
        getData(abc)
        $('.zzc-wp').css({
            display: "none"
        })
        getInfo(shopToken, area)
        $('.nav-content-btn-jq').text(0)
        let iptArr = $('.gxkAll')
        for (var i = 0; i < iptArr.length; i++) {
            iptArr.eq(i).prop("checked", false)
        }
        for (var c = 0; c < xgjsAJaxArr.length; c++) {
            xgstate({
                cid: xgjsAJaxArr[c].id,
                num: xgjsAJaxArr[c].num
            })
        }

    })

    //发送请求修改状态
    function xgstate(data) {
        console.log(data)
        $.ajax({
            url: "http://localhost:2020/jiesuan/updateState",
            type: "POST",
            data,
            success(res) {
                // console.log(res)
            }
        })
    }

    //获取个人信息
    function getInfo(token, area) {
        $.ajax({
            url: "http://localhost:2020/user/info",
            type: "GET",
            data: {
                token
            },
            success(res) {
                userArr = res.data
                // console.log(userArr)
                if (area) {
                    xdData({
                        id: res.data.id,
                        area: area
                    })
                }
            }
        })
    }

    //修改地址
    function xdData({
        id,
        area
    }) {
        console.log(area)
        $.ajax({
            url: "http://localhost:2020/user/xgdizhi",
            type: "POST",
            data: {
                id: id,
                area: JSON.stringify(area)
            },
            success(res) {
                var parent = $(".zzc-wp")
                parent.css({
                    display: "none"
                })
            }
        })
    }


    //请求拿数据
    function getData(id) {
        if (id.length != 0) {
            $.ajax({
                url: "http://localhost:2020/question/getDeail",
                type: "GET",
                data: {
                    id: id.join(",")
                },
                success(res) {
                    let a = res.data.data.map((v, i) => {
                        v["num"] = idArr[i].num
                        return v
                    })
                    dataArr = a
                    xrFn(a)
                }
            })
        } else {
            xrFn([])
        }
    }

    //渲染结算
    function xrjs(dataArr) {
        var arr = []
        for (var i = 0; i < dataArr.length; i++) {
            arr.push('<div class="nav-content-sp1">\
            <ul class="nav-content-sp-ul">\
                                    <li class="nav-content-sp-ul-li1">\
                                        <img src="http://localhost:2020/uploads/', dataArr[i].avatar, '" alt="">\
                                        <div>\
                                            <div>', dataArr[i].name, '</div>\
                                        </div>\
                                    </li>\
                                    <li class="nav-content-sp-ul-li3">\
                                        <div style="color: #ccc;text-decoration:line-through;">￥', dataArr[i].Originalprice, '</div>\
                                        <div>￥<span class="jiage1">', dataArr[i].price, '</span>.00</div>\
                                    </li>\
                                    <li class="nav-content-sp-ul-li5">\
                                        <span class="sp">', dataArr[i].num, '</span>\
                                    </li>\
                                    <li style="color: red;font-size: 13px;">￥<span class="jiage">', dataArr[i].price * dataArr[i].num, '</span>.00</li>\
                                </ul>\
                                </div>')
        }
        $(".nav-content-shop1").html(arr.join(""))
    }

    //渲染
    function xrFn(dataArr) {
        var arr = []
        if (dataArr.length == 0) {
            arr.push("<div class='zusj'><div>暂无数据</div><div/>")
        } else {
            for (var i = 0; i < dataArr.length; i++) {
                arr.push('<div class="nav-content-sp">\
                <ul class="nav-content-sp-ul">\
                                        <li class="nav-content-sp-ul-li1">\
                                            <input data-id="', dataArr[i].id, '" data-i="', i, '" class="gxk" type="checkbox" name="" id="gxk">\
                                            <img src="http://localhost:2020/uploads/', dataArr[i].avatar, '" alt="">\
                                            <div class="name-wp">\
                                                <div>', dataArr[i].name, '</div>\
                                            </div>\
                                        </li>\
                                        <li class="nav-content-sp-ul-li3">\
                                            <div style="color: #ccc;text-decoration:line-through;">￥', dataArr[i].Originalprice, '</div>\
                                            <div>￥<span class="jiage1">', dataArr[i].price, '</span>.00</div>\
                                        </li>\
                                        <li class="nav-content-sp-ul-li5">\
                                            <button data-i="', i, '" class="jian">-</button>\
                                            <span class="sp">', dataArr[i].num, '</span>\
                                            <button data-i="', i, '" class="jia">+</button>\
                                        </li>\
                                        <li style="color: red;font-size: 13px;">￥<span class="jiage">', dataArr[i].price * dataArr[i].num, '</span>.00</li>\
                                        <li class="nav-content-sp-ul-li7">\
                                            <div  data-id="', dataArr[i].id, '" class="delData" data-i="', i, '">删除</div>\
                                        </li>\
                                    </ul>\
                                    </div>')
            }
        }
        $(".nav-content-shop").html(arr.join(""))
    }
}(window, document, jQuery))